package com.znyj.servlet.mainController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.znyj.servlet.entity.MerchantEntity;
import com.znyj.servlet.model.MerchantQueryModel;
import com.znyj.servlet.service.MerchantService;
import com.znyj.servlet.utilsTool.CommonTool;
import com.znyj.servlet.vo.Page;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by gaoliwei02 on 2017/10/19.
 */
@Controller
@RequestMapping(value = "/merchant")
public class MerchantController {

    @Resource
    private MerchantService merchantService;

    /*-----------------------------PAGE-----------------------------------------------------*/
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    protected String index(HttpServletRequest request) throws ParseException, IOException {
        return "/page/merchant_page";
    }

    @RequestMapping(value = "/getlist.inner", method = RequestMethod.POST)
    protected
    @ResponseBody
    String getListInner(@RequestBody String receiveData) throws ParseException, IOException {
        MerchantQueryModel merchantQueryModel = new MerchantQueryModel(receiveData);//string到pojo
        Page<MerchantEntity> page = merchantService.createMerchantPage(merchantQueryModel);//从数据库获取实体列表
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").disableHtmlEscaping().create();
        return gson.toJson(page);
    }

    @RequestMapping(value = "/bind")
    public String bindPage(HttpSession session) throws Exception {
        return "/page/merchant_bind_page";
    }

    @RequestMapping(value = "/modify/{poiid}", method = RequestMethod.GET)
    public String modifyPage(HttpSession session, @PathVariable(value = "poiid") int poiid, HttpServletRequest request) throws Exception {
        Map<String, Object> model = new HashMap<String, Object>();

        MerchantEntity merchantEntity = merchantService.findByPoiid(poiid);

        //对比session名字与update的BD名字是否相同
        String bdName = (String) session.getAttribute("username");
        Integer rolePermission = (Integer) session.getAttribute("rolePermission");

        if (rolePermission > 0 && rolePermission < 4) {

        } else if (CommonTool.isNullOrInvalid(bdName) || CommonTool.isNullOrInvalid(bdName)) {
            return "/no_access";
        } else if (!merchantEntity.getBdName().equals(bdName)) {
            return "/no_access";
        }


        if (merchantEntity == null) {
            model.put("poiid", merchantEntity.getPoiid());
            request.setAttribute("model", model);
        } else {
            model.put("poiid", merchantEntity.getPoiid());
            model.put("merchant_name", merchantEntity.getMerchantName());
            model.put("merchant_address", merchantEntity.getMerchantAddress());
            model.put("city_area", merchantEntity.getCityArea());
            model.put("phone_number", merchantEntity.getPhoneNumber());
            model.put("open_info", merchantEntity.getOpenInfo());
            model.put("wifi", merchantEntity.getWifi());
            model.put("usage_fee", merchantEntity.getUsageFee());
            model.put("device_list", merchantEntity.getDeviceList());

            request.setAttribute("model", model);
        }
        return "/page/merchant_modify_page";
    }

    @RequestMapping(value = "/bind_info.inner", method = RequestMethod.POST)
    protected
    @ResponseBody
    String bindInfoInner(@RequestBody String receiveData, HttpSession session) throws ParseException, IOException {
        JSONObject getJson = JSON.parseObject(receiveData);
        MerchantEntity merchantEntity = new MerchantEntity();

        JSONArray array = getJson.getJSONArray("device_list");
        String device_list = "";
        for (int i = 0; i < array.size(); i++) {
            device_list += array.get(i) + ";";
        }
        long lastPoiid = merchantService.findNewestPoiid() + 1;


        merchantEntity.setPoiid(lastPoiid);
        merchantEntity.setBdName((String) session.getAttribute("username"));
        merchantEntity.setRegisterTime(new Timestamp(System.currentTimeMillis()));
        merchantEntity.setPhoneNumber(getJson.getString("phone_number"));
        merchantEntity.setRolePermission(10);
        merchantEntity.setDeviceList(device_list);
        merchantEntity.setOpenInfo(getJson.getString("open_info"));
        merchantEntity.setWifi(getJson.getString("wifi").equals("yes") ? 1 : 0);
        merchantEntity.setCityArea(getJson.getString("city_area"));
        merchantEntity.setMerchantName(getJson.getString("merchant_name"));
        merchantEntity.setMerchantAddress(getJson.getString("merchant_address"));
        merchantEntity.setUsageFee(getJson.getString("usage_fee"));

        merchantService.insertMerchant(merchantEntity);
        return "" + lastPoiid;
    }

    @RequestMapping(value = "/update_info.inner", method = RequestMethod.POST)
    protected
    @ResponseBody
    String updateInfoInner(@RequestBody String receiveData, HttpSession session) throws ParseException, IOException {
        JSONObject getJson = JSON.parseObject(receiveData);
        MerchantEntity merchantEntity = new MerchantEntity();

        JSONArray array = getJson.getJSONArray("device_list");
        String device_list = "";
        for (int i = 0; i < array.size(); i++) {
            device_list += array.get(i) + ";";
        }

        merchantEntity.setPoiid(getJson.getInteger("poiid"));
        merchantEntity.setRegisterTime(new Timestamp(System.currentTimeMillis()));
        merchantEntity.setPhoneNumber(getJson.getString("phone_number"));
        merchantEntity.setDeviceList(device_list);
        merchantEntity.setOpenInfo(getJson.getString("open_info"));
        merchantEntity.setWifi(getJson.getString("wifi").equals("yes") ? 1 : 0);
        merchantEntity.setCityArea(getJson.getString("city_area"));
        merchantEntity.setMerchantName(getJson.getString("merchant_name"));
        merchantEntity.setMerchantAddress(getJson.getString("merchant_address"));
        merchantEntity.setUsageFee(getJson.getString("usage_fee"));

        merchantService.updateMerchant(merchantEntity);
        return "ok";
    }
}
